﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using ERPStore.Extensions;

using ERPStore.Web.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Diagnostics.Controllers
{
	public class FeedbackController : Controller
	{
		public FeedbackController(ERPStore.Services.IEmailerService emailerService
			, ERPStore.Web.Services.IEmailTemplateService emailTemplateService)
		{
			EmailerService = emailerService;
			EmailTemplateService = emailTemplateService;
		}

		protected ERPStore.Services.IEmailerService EmailerService { get; private set; }
		protected ERPStore.Web.Services.IEmailTemplateService EmailTemplateService { get; private set; }

		public ActionResult ShowForm()
		{
			var feedback = new Models.Feedback();
			var principal = (ERPStore.Models.UserPrincipal)User;
			if (principal.CurrentUser != null)
			{
				feedback.UserName = principal.CurrentUser.FullName;
			}
			ViewData.Model = feedback;
			return PartialView("_feedbackform");
		}

		[HttpPost]
		public ActionResult ShowForm(Models.Feedback feedback)
		{
			if (feedback.CurrentUrl.IsNullOrTrimmedEmpty())
			{
				return View("_feedbackform");
			}

			if (feedback.Message.IsNullOrTrimmedEmpty())
			{
				ModelState.AddModelError("message", "vous devez indiquer un message");
			}

			if (!ModelState.IsValid)
			{
				return View("_feedbackform");
			}

			var cookie = (Request.Headers != null) ? Request.Headers["Cookie"] : string.Empty;

			feedback.UserHostAddress = Request.UserAgent;
			feedback.UserAgent = Request.UserAgent;
			// feedback.Cookie = cookie;
			// feedback.UrlReferrer = (Request.UrlReferrer != null) ? Request.UrlReferrer.PathAndQuery : string.Empty;
			feedback.VisitorId = ((ERPStore.Models.UserPrincipal) User).VisitorId;

			var emailTemplate = EmailTemplateService.GetTemplate("feedback", feedback);
			EmailerService.Send(emailTemplate);

			ViewBag.IsSent = true;

			ViewBag.Message = "Votre message à bien été envoyé";
			return PartialView("_feedbacksent");
		}
	}
}
